package com.icee.myth.console;

import com.icee.myth.common.encoder.Type2BytesLengthFieldProtobufEncoder;
import com.icee.myth.common.message.serverMessage.InternalChannelMessage;
import com.icee.myth.common.message.serverMessage.Message;
import com.icee.myth.console.channelHandler.ConsoleToManagerHandler;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.net.InetSocketAddress;

/**
 * @author liuxianke
 */
public class ConsoleToManagerClient {

    //Singleton
    private static ConsoleToManagerClient INSTANCE = new ConsoleToManagerClient();

    private String host; // Server的主机地址
    private int port; // Server的端口地址
    private Bootstrap bootstrap;
    private Channel managerChannel; // channelContext connect to server

    //getInstance操作的第一次调用在Main的start中，因此无需同步
    public static ConsoleToManagerClient getInstance() {
        return INSTANCE;
    }

    private ConsoleToManagerClient() {
    }

    public void init(String host, int port) {
        this.host = host;
        this.port = port;

        this.bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 2, 4, 0, 0))
                                .addLast("consoleToManagerEncoder", new Type2BytesLengthFieldProtobufEncoder())
                                .addLast("targetHandler", new ConsoleToManagerHandler());
                    }
                });
    }

    public void connectToServer() {
        // 连接服务
        // Start the connection attempt.
        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_INFO, "Connecting to server...");
        bootstrap.connect(new InetSocketAddress(host, port));
    }

    public Channel getManagerChannel() {
        return managerChannel;
    }

    public void handleMessage(Message message) {
        switch (message.getType()) {
            case CONSOLE_MANAGER_CONNECT: {
                // 处理ManagerConnect消息
                assert (managerChannel == null);
                managerChannel = ((InternalChannelMessage) message).channel;

                MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_INFO, "Manager connected!");
                break;
            }
            case CONSOLE_MANAGER_CLOSE: {
                // 处理ClusterClose消息
                managerChannel = null;
                MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_INFO, "Manager closed!");

                break;
            }
        }
    }
}
